use std::collections::HashMap;

use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::{common::HTTP_METHOD, error::AppError};

#[derive(Debug, Serialize, Deserialize)]
pub struct Response<T> {
    pub status: u64,
    pub msg: String,
    pub datas: T,
}

impl<T> Response<T> {
    pub fn new(status: u64, msg: String, datas: T) -> Self {
        Response { status, msg, datas }
    }
}

pub async fn request<T>(
    method: HTTP_METHOD,
    api_url: &str,
    param: HashMap<String, String>,
) -> Result<T, AppError>
where
    T: DeserializeOwned,
{
    match method {
        HTTP_METHOD::GET => {
            let resp = reqwest::Client::new()
                .get(api_url)
                .query(&param)
                .send()
                .await?
                .json::<T>()
                .await?;
            Ok(resp)
        }
        HTTP_METHOD::POST => {
            let resp = reqwest::Client::new()
                .post(api_url)
                .form(&param)
                .send()
                .await?
                .json::<T>()
                .await?;
            Ok(resp)
        }
    }
}
